/**
 * Created by shidaiapp on 2017/10/16.
 */
import tiyAddEditData from "./add_edit_data";
import {isNotEmpty} from "../../../js/commonUtils";

function changeModelColorLoading(self, tiyData) {
  tiyData.tStatus.modalColorModify.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalColorModify.isLoading = true;
  });
}

/**
 * 修改产品信息
 * @param self
 * @param tiyData
 * @param index
 * @param isEdit
 */
export const modifyProduct = (self, tiyData, id, isEdit) => {
  tiyData.tStatus.modalModify.isLoading = false;
  tiyData.tParam.productTabs = 'product';
  tiyData.tStatus.modalModify.isEditDetail = isEdit;
  tiyData.tStatus.modalModify.closable = isEdit;
  self.$refs.AProductAddEdit.$refs['paramProductSimple'].resetFields();
  self.$Spin.show();
  self.$apiProduct.getProductById({id: id}).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let product = response.result.product;
      let productTabs = response.result.productTabs;
      let productArgs = response.result.productArgs;
      let productColors = response.result.productColors;
      let customSizes = response.result.customSizeList;
      let sysSizes = response.result.sysSizeList;
      let productPrices = response.result.productPriceList;
      let productManageTabs = response.result.manageTabs;
      let productClassifications = response.result.classificationList;
      let importInfo = response.result.importInfo;
      let videos= response.result.videos;

      //产品色卡
      tiyData.tData.productColorList.splice(0,tiyData.tData.productColorList.length);
      if(productColors.length>0){
        productColors.forEach(function(item){
          tiyData.tData.productColorList.push(item)
        })
      }

      //产品标签
      tiyData.tParam.paramProduct.tab = '';
      if(productTabs.length>0){
        tiyData.tParam.paramProduct.tab=productTabs[0].tabId;
      };

      //产品管理标签
      tiyData.tParam.paramProduct.manageTabIds = [];
      if(productManageTabs.length>0) {
        productManageTabs.forEach(function (item) {
          tiyData.tParam.paramProduct.manageTabIds.push(item.id);
        });
      }

      //产品尺码类型
      tiyData.tParam.paramProduct.sysSizeType = product.sizeType;

      //产品分类
      tiyData.tParam.paramProduct.classificationIds.length=0;
      if (null != productClassifications) {
        productClassifications.forEach(function (item) {
          if(item){
            tiyData.tParam.paramProduct.classificationIds.push(item.id);
          }
        });
      }

      //产品价格
      tiyData.tParam.paramProduct.priceList.splice(0, tiyData.tParam.paramProduct.priceList.length);
      if(productPrices.length>0) {
        productPrices.forEach(function(item){
          if(item.min==''||item.price==''){
            this.$Message.error('价格不能为空') ;
            return;
          }
          tiyData.tParam.paramProduct.priceList.push({'min':item.min,'price':item.price});
        })
      }else{
        tiyData.tParam.paramProduct.priceList.push({min:null,price:0});
      }

      //产品自定义尺码表
      tiyData.tParam.paramProduct.customSize.splice(0, tiyData.tParam.paramProduct.customSize.length);
      customSizes.forEach(function(item){
        tiyData.tParam.paramProduct.customSize.push({id:item.id,name:item.name,sequence:item.sequence});
      })

      tiyData.tParam.paramProduct.videos.splice(0, tiyData.tParam.paramProduct.videos.length);
      tiyData.tParam.paramProduct.videos.push(...videos);

      let productSizeDetail = response.result.productSizeDetail;
      tiyData.tParam.productSizeTable.rowCount =0;
      tiyData.tParam.productSizeTable.columnCount = 0;
      tiyData.tParam.productSizeTable.title = '';
      tiyData.tParam.productSizeTable.subTitle ='';
      tiyData.tData.productSizeDetail.length=0;
      tiyData.tParam.paramProduct.useTranslateSizeTableTool = false;
      tiyData.tParam.paramProduct.sizeTable.splice(0);
      if(productSizeDetail!=''&&productSizeDetail!=null){
        tiyData.tParam.paramProduct.sizeTableType = 1;
        tiyData.tParam.paramProduct.hasSizeTable = true;
        let sizeTable = self.$toJson(productSizeDetail.content);
        tiyData.tParam.paramProduct.sizeTable.push(...sizeTable);
        sizeTable.forEach(function(item){
          let rowData = new Object();
          for(let i=0;i<productSizeDetail.colNumber;i++){
            rowData['Column'+i] = item[i];
          }
          tiyData.tData.productSizeDetail.push(rowData);
        });
        //尺码表添加一个空行，用于构造删除列
        let rowData = new Object();
        for(let i=0;i<productSizeDetail.colNumber;i++){
          rowData['Column'+i] = "";
        }
        tiyData.tData.productSizeDetail.push(rowData);

        tiyData.tParam.productSizeTable.rowCount = productSizeDetail.rowNumber;
        tiyData.tParam.productSizeTable.columnCount = productSizeDetail.colNumber;
        tiyData.tParam.productSizeTable.title = productSizeDetail.title;
        tiyData.tParam.productSizeTable.subTitle = productSizeDetail.subTitle;
        createSizeTableTitles(self, tiyData);
      } else {
        tiyData.tParam.paramProduct.sizeTableType = 0;
        tiyData.tParam.paramProduct.hasSizeTable = false;
      }

      tiyData.tParam.sysSizeTypeChange = 0;
      tiyData.tParam.paramProduct.id = product.id;
      tiyData.tParam.paramProduct.productCode = product.code;
      tiyData.tParam.paramProduct.productName = product.name;
      tiyData.tParam.paramProduct.isTop = product.sequence > 0;
      tiyData.tParam.paramProduct.listImgUrl = product.listImgUrl;
      tiyData.tParam.paramProduct.productWeight = product.weight;
      tiyData.tParam.paramProduct.productMaterial = product.material;
      tiyData.tParam.paramProduct.sequence = product.sequence;
      tiyData.tParam.paramProduct.productGender = product.gender;
      tiyData.tParam.paramProduct.productState = product.state;
      tiyData.tParam.paramProduct.productIsUnisex = product.isUnisex;
      tiyData.tParam.paramProduct.shelves = product.shelves;
      tiyData.tParam.paramProduct.priceUnit=product.priceUnit;
      tiyData.tParam.paramProduct.keyword = product.keyword;
      tiyData.tParam.paramProduct.note = product.note;
      tiyData.tParam.paramProduct.description = product.description;
      tiyData.tParam.paramProduct.countWeight = product.countWeight;

      //产品系统尺码
      tiyData.tParam.paramProduct.sysSizeIds.splice(0, tiyData.tParam.paramProduct.sysSizeIds.length);
      sysSizes.forEach(function(item){
        tiyData.tParam.paramProduct.sysSizeIds.push(item.sysSizeId);
      });

      //产品尺码图片
      tiyData.tParam.paramProduct.productSizeImages.splice(0, tiyData.tParam.paramProduct.productSizeImages.length);
      let sizePics = response.result.productSizePics;
      if(sizePics!=null&&sizePics!=''){
        sizePics.forEach(function(item){
          tiyData.tParam.paramProduct.productSizeImages.push(
            {sequence:item.sequence,width:item.width,height:item.height,url:item.url}
          )
        })
      };

      //产品属性
      tiyData.tParam.paramProduct.argJson.splice(0);
      if(productArgs.length>0) {
        productArgs.forEach(function (item) {
          tiyData.tParam.paramProduct.argJson.push({name: item.paramName, value: item.paramValue});
        });
      }else{
        tiyData.tParam.paramProduct.argJson.push({name: 'Weight', value: ''});
        tiyData.tParam.paramProduct.argJson.push({name: 'Material', value: ''});
      }
      //产品图片
      let productImages = response.result.productImageList;
      tiyData.tParam.paramProduct.showImage={};
      tiyData.tParam.paramProduct.showImage200w="";
      tiyData.tParam.paramProduct.mainImages.splice(0,tiyData.tParam.paramProduct.mainImages.length);
      tiyData.tParam.paramProduct.detailImages.splice(0,tiyData.tParam.paramProduct.detailImages.length);
      productImages.forEach(item=>{
        if(item.type==1){
          tiyData.tParam.paramProduct.showImage = item;
          if(item!=null){
            tiyData.tParam.paramProduct.showImage200w=self.yunPath+item.originalImagePath;
            if(item.zipImages!=null){
              let zipImgs=eval(item.zipImages);
              zipImgs.forEach(function (item){
                if(item.size=="200w"){
                  tiyData.tParam.paramProduct.showImage200w=self.yunPath+item.imagePath;
                }
              })
            }
          }
        }
        if(item.type==2){
          item.zipImg=item.originalImagePath;
          if(item.zipImages!=null){
            let zipImgs=eval(item.zipImages);
            zipImgs.forEach(function (tem){
              if(tem.size=="200w"){
                item.zipImg=tem.imagePath;
              }
            })
          }
          tiyData.tParam.paramProduct.mainImages.push(item);
        }
        if(item.type==3){
          tiyData.tParam.paramProduct.detailImages.push(item);
        }
      });

      let comparePrice = product.comparePrice;
      if(comparePrice){
        tiyData.tParam.paramProduct.comparePrice.isUploadComparePrice = true;
        tiyData.tParam.paramProduct.comparePrice.ratio = comparePrice.cheapRatio;
        tiyData.tParam.paramProduct.comparePrice.images = comparePrice.images;
      } else {
        tiyData.tParam.paramProduct.comparePrice.isUploadComparePrice = false;
        tiyData.tParam.paramProduct.comparePrice.ratio = 0;
        tiyData.tParam.paramProduct.comparePrice.images = [];
      }
      tiyData.tParam.paramProduct.comparePrice.otherPrice =0;
      if(tiyData.tParam.paramProduct.priceList && tiyData.tParam.paramProduct.priceList[0]){
        tiyData.tParam.paramProduct.comparePrice.productPrice = tiyData.tParam.paramProduct.priceList[0].price;
      } else {
        tiyData.tParam.paramProduct.comparePrice.productPrice = 0;
      }
      //导入货源ID
      tiyData.tParam.paramProduct.collectionId = product.collectionId;
      //导入货源原始数据
      tiyData.tData.productImportInfo.createTime = 0;
      tiyData.tData.productImportInfo.createUser = "";
      tiyData.tData.productImportInfo.profitRatio = 0;
      tiyData.tData.productImportInfo.originInfo.author = "";
      tiyData.tData.productImportInfo.originInfo.weight = 0;
      tiyData.tData.productImportInfo.originInfo.categories.splice(0);
      tiyData.tData.productImportInfo.originInfo.prices.splice(0);
      if(importInfo != null) {
        tiyData.tData.productImportInfo.createTime = importInfo.createTime;
        tiyData.tData.productImportInfo.createUser = importInfo.createUser;
        tiyData.tData.productImportInfo.profitRatio = importInfo.profitRatio;
        if(isNotEmpty(importInfo.originInfo)) {
          let originInfo = self.$toJson(importInfo.originInfo);
          tiyData.tData.productImportInfo.originInfo.author = originInfo.author;
          tiyData.tData.productImportInfo.originInfo.weight = originInfo.weight;
          tiyData.tData.productImportInfo.originInfo.categories.push(...originInfo.categories);
          tiyData.tData.productImportInfo.originInfo.prices.push(...originInfo.prices);
        }
      }

        //构造分类树形菜单
      makeClassificationTree(self, tiyData);
      //显示弹窗
      tiyData.tStatus.modalModify.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
      tiyData.tStatus.modalModify.closable = true;
    }
  });
};
/**
 * 修改产品色卡信息
 * @param self
 * @param tiyData
 * @param index
 */
export const productColorAdd = (self, tiyData) => {
  tiyData.tParam.productColor.id = '';
  tiyData.tParam.productColor.colorName = '';
  tiyData.tParam.productColor.cnName = '';
  tiyData.tParam.productColor.productId = tiyData.tParam.paramProduct.id;
  tiyData.tParam.productColor.productCode = tiyData.tParam.paramProduct.productCode;
  tiyData.tParam.productColor.suggestedPrice = '';
  tiyData.tParam.productColor.currentPrice = '';
  tiyData.tParam.productColor.colorImg = '';
  tiyData.tParam.productColor.iconImg = '';
  for(let key in tiyData.tParam.productColor.iconImage){
    delete tiyData.tParam.productColor.iconImage[key];
  }
  for(let key in tiyData.tParam.productColor.colorImage){
    delete tiyData.tParam.productColor.colorImage[key];
  }
  tiyData.tParam.productColor.detailImages.splice(0,tiyData.tParam.productColor.detailImages.length);
  // tiyData.tParam.productColor.stock = '';
  tiyData.tParam.productColor.description = '';
  tiyData.tParam.productColor.isDefault = 0;
  self.$ySpliceAll(tiyData.tParam.productColor.detailImage);
  tiyData.tParam.productColor.originalColorImg = '';
  tiyData.tStatus.modalColorModify.isShow = true;
  tiyData.tStatus.isCheckDefaultDisabled= false ;
  self.$ySpliceAll(tiyData.tParam.productColor.colorSizeIds,tiyData.tParam.productColor.colorSizeSelected);
  tiyData.tStatus.modalColorModify.title = '新增色卡';
  self.$refs['paramProductColorSimple'].resetFields();
  //新增色卡时默认选中全部尺码，并设置默认库存
  tiyData.tParam.productColor.productSizes.forEach(function(item){
    let colorSize = {
      id: item.id,
      sizeName: item.sizeName,
      selfDesignSize: item.selfDesignSize,
      sysSizeType:item.sysSizeType,
      stock: 100000
    };
    let idStr = '{\'id\':\''+item.id+'\',\'name\':\''+item.sizeName+'\',\'selfDesignSize\':'+item.selfDesignSize+'}';
    tiyData.tParam.productColor.colorSizeIds.push(idStr);
    tiyData.tParam.productColor.colorSizeSelected.push(colorSize);
  });
  self.productSizeChangeState = false;
};

/**
 * 修改色卡信息
 * @param self
 * @param tiyData
 * @param index
 */
export const productColorModify = (self, tiyData, index) => {
  self.$refs['paramProductColorSimple'].resetFields();
  let productColor = tiyData.tData.productColorList[index];
  tiyData.tParam.productColor.id = productColor.id;
  self.$apiProduct.getProductColorById({id:productColor.id}).then(
    function (response) {
      productColor.sizes = [];
      response.result.sizes.forEach(function(item){
        productColor.sizes.push(item);
      });
    }
  );
  tiyData.tParam.productColor.colorName = productColor.colorName;
  tiyData.tParam.productColor.cnName = productColor.cnName;
  tiyData.tParam.productColor.productId = tiyData.tParam.paramProduct.id;
  tiyData.tParam.productColor.productCode = tiyData.tParam.paramProduct.productCode;
  tiyData.tParam.productColor.suggestedPrice = productColor.suggestedPrice;
  tiyData.tParam.productColor.currentPrice = productColor.currentPrice;
  tiyData.tParam.productColor.colorImage = productColor.colorImage;
  tiyData.tParam.productColor.iconImage = productColor.iconImage;
  if(productColor.detailImages!=null){
    tiyData.tParam.productColor.detailImages = productColor.detailImages;
  }
  // tiyData.tParam.productColor.stock = productColor.stock;
  tiyData.tParam.productColor.description = productColor.description;
  tiyData.tParam.productColor.isDefault = productColor.isDefault;
  if(tiyData.tParam.productColor.isDefault === 1){
    tiyData.tStatus.isCheckDefaultDisabled= true;
  } else {
    tiyData.tStatus.isCheckDefaultDisabled= false;
  }
  tiyData.tParam.productColor.originalColorImg = productColor.colorImg;

  let detailImage = [];
  if(productColor.colorImages){
    productColor.colorImages.forEach(function (item) {
      detailImage.push(item.originalImagePath);
    });
  }

  tiyData.tParam.productColor.detailImage = detailImage;

  tiyData.tParam.productColor.colorSizeIds=[];
  tiyData.tParam.productColor.colorSizeSelected.length=0;
  productColor.sizes.forEach(function(item){
    tiyData.tParam.productColor.colorSizeSelected.push({
      id: item.productSizeId,
      sizeName: item.sizeName,
      stock: item.stock,
      selfDesignSize: item.selfDesignSize,
      overstock: item.overstock
    });

    let colorsizeId = '{\'id\':\''+item.productSizeId+'\',\'name\':\''+item.sizeName+'\',\'selfDesignSize\':'+item.selfDesignSize+'}';
    tiyData.tParam.productColor.colorSizeIds.push(colorsizeId);
  })

  tiyData.tStatus.modalColorModify.title = '编辑色卡';
  tiyData.tStatus.modalColorModify.isShow = true;
  self.productSizeChangeState = false;
};

/**
 * 保存产品色卡信息到服务器
 * @param self
 * @param tiyData
 * @param index
 */
export const productColorWebAddOrModify = (self, tiyData, name) => {
  self.$refs[name].validate((valid) => {
    if (valid) {
      if(!tiyData.tParam.productColor.colorSizeSelected || tiyData.tParam.productColor.colorSizeSelected.length <= 0){
        self.$Modal.info({content:'没有设置尺码信息!'});
        tiyData.tStatus.modalColorModify.isLoading = false;
        return;
      }
      if(Object.keys(tiyData.tParam.productColor.iconImage).length==0){
        self.$Modal.info({content:'色卡图标不能为空!'});
        tiyData.tStatus.modalColorModify.isLoading = false;
        return ;
      }
      if(Object.keys(tiyData.tParam.productColor.colorImage).length==0){;
        self.$Modal.info({content:'色卡主图不能为空!'});
        tiyData.tStatus.modalColorModify.isLoading = false;
        return ;
      }

      self.$Spin.show();
      tiyData.tStatus.modalColorModify.isLoading = true;
      let parms = {
        id: tiyData.tParam.productColor.id,
        colorName: tiyData.tParam.productColor.colorName,
        cnName: tiyData.tParam.productColor.cnName,
        productId: tiyData.tParam.productColor.productId,
        productCode: tiyData.tParam.productColor.productCode,
        state: tiyData.tParam.productColor.state,
        description: tiyData.tParam.productColor.description,
        isDefault: tiyData.tParam.productColor.isDefault,
        iconImage: JSON.stringify(tiyData.tParam.productColor.iconImage),
        colorImage: JSON.stringify(tiyData.tParam.productColor.colorImage),
        detailImages: JSON.stringify(tiyData.tParam.productColor.detailImages),
        colorSizes:tiyData.tParam.productColor.colorSizeSelected
      };
      self.$apiProduct.addEditProductColor(parms)
        .then(function (response) {
          self.$Spin.hide();
          if (response.success) {
            tiyData.tStatus.modalColorModify.isShow = false;
            self.$Modal.success({content:'保存成功!'});

            self.$apiProduct.getProductColorsByProductId({"productId":tiyData.tParam.productColor.productId})
              .then(function(response){
                if(response.success){
                  tiyData.tData.productColorList.splice(0);
                  response.result.forEach(function(item){
                    tiyData.tData.productColorList.push(item);
                  })
                }
              })
          } else {
            tiyData.tStatus.modalColorModify.isLoading = false;
            self.$Modal.error({content:response.errorMessage});
          }
        });
    } else {
      changeModelColorLoading(self, tiyData);
    }
  });
};
/**
 * 保存产品信息到服务器
 * @param self
 * @param tiyData
 * @param index
 */
export const webModify = (self, tiyData, name) => {
  tiyData.tStatus.modalModify.isLoading = true;
  self.$Spin.show();
  let paramProduct = tiyData.tParam.paramProduct;
  self.$refs[name].validate((valid) => {
    if (valid) {
      let argJson = [];
      let priceJson=[];

      paramProduct.argJson.forEach(function (item) {
        if ('' != item.value) {
          argJson.push({paramName: item.name, paramValue: item.value});
        }
      });

      paramProduct.priceList.forEach(function (item) {
        if ('' != item.min && 0!=item.price) {
          priceJson.push({price: item.price, min: item.min});
        }
      });

      if(paramProduct.productState === 0 && priceJson.length <= 0){
        self.$Spin.hide();
        self.$Modal.error({content:"已上架产品必须输入价格信息，并且价格需要大于0！",closable:true});
        tiyData.tStatus.modalModify.isLoading = false;
        return ;
      }

      if(paramProduct.comparePrice.isUploadComparePrice && (!paramProduct.comparePrice.ratio || paramProduct.comparePrice.images.length <= 0)){
        self.$Spin.hide();
        self.$Modal.error({content:"必须填入大于0的比价比率并且上传比价图片！",closable:true});
        tiyData.tStatus.modalModify.isLoading = false;
        return ;
      }

      let detailData = new Array();
      let columnCount = 0;
      let rowCount = 0;
      if(tiyData.tParam.paramProduct.hasSizeTable) {
        if(tiyData.tParam.paramProduct.useTranslateSizeTableTool) {
          if(tiyData.tParam.paramProduct.sizeTable==null || tiyData.tParam.paramProduct.sizeTable.length < 2 || tiyData.tParam.paramProduct.sizeTable[0].length < 2) {
            self.$Spin.hide();
            self.$Modal.error({content:"定义尺码详情表时必须超过2行2列！",closable:true});
            return;
          }
          rowCount = tiyData.tParam.paramProduct.sizeTable.length;
          columnCount = tiyData.tParam.paramProduct.sizeTable[0].length;
          detailData.push(...tiyData.tParam.paramProduct.sizeTable);
        }else{
          columnCount = tiyData.tParam.productSizeTable.columnCount;
          rowCount = tiyData.tParam.productSizeTable.rowCount;
          if((rowCount > 0 && rowCount < 2) || (columnCount > 0 && columnCount < 2)){
            self.$Spin.hide();
            self.$Modal.error({content:"定义尺码详情表时必须超过2行2列！",closable:true});
            tiyData.tStatus.modalModify.isLoading = false;
            return ;
          }
          if(tiyData.tData.productSizeDetail.length==0){
            rowCount=0;
            columnCount=0;
          }
          for(let i = 0; i < rowCount; i++){
            let row = tiyData.tData.productSizeDetail[i];
            let valueArray=new Array();
            for(let j=0;j<columnCount;j++){
              let columnName = 'Column'+j;
              if(i==0 && j==0){
                valueArray.push('Size')
              }else{
                valueArray.push(row[columnName])
              }
            }
            detailData.push(valueArray)
          }
        }
      }

      if(tiyData.tParam.paramProduct.priceUnit==0){
        self.$Spin.hide();
        self.$Modal.error({content:"请选择价格单位！",closable:true});
        tiyData.tStatus.modalModify.isLoading = false;
        return ;
      }
      if(Object.keys(tiyData.tParam.paramProduct.showImage).length==0){
        self.$Spin.hide();
        self.$Modal.error({content:"橱窗图不能为空！",closable:true});
        tiyData.tStatus.modalModify.isLoading = false;
        return ;
      }

      let param = {
        id: tiyData.tParam.paramProduct.id,
        productCode: tiyData.tParam.paramProduct.productCode,
        productName: tiyData.tParam.paramProduct.productName,
        isTop: tiyData.tParam.paramProduct.isTop ? 1 : 0,
        typeValueParent: tiyData.tParam.paramProduct.typeValueParent,
        typeValues: tiyData.tParam.paramProduct.typeValues,
        classificationIds:tiyData.tParam.paramProduct.classificationIds.toString(),
        tabs: tiyData.tParam.paramProduct.tab,
        manageTabIds: tiyData.tParam.paramProduct.manageTabIds.toString(),
        shelves: tiyData.tParam.paramProduct.shelves,
        productWeight: tiyData.tParam.paramProduct.productWeight,
        productMaterial: tiyData.tParam.paramProduct.productMaterial,
        productGender: tiyData.tParam.paramProduct.productGender,
        productIsUnisex: tiyData.tParam.paramProduct.productIsUnisex ? 1 : 0,
        productState: tiyData.tParam.paramProduct.productState,
        priceUnit: tiyData.tParam.paramProduct.priceUnit,
        argJson: JSON.stringify(argJson),
        priceJson: JSON.stringify(priceJson),
        countWeight:tiyData.tParam.paramProduct.countWeight,
        interferenceFactor:90,
        sysSizeIds:tiyData.tParam.paramProduct.sysSizeIds.toString(),
        sysSizeType:tiyData.tParam.paramProduct.sysSizeType,
        customSize:JSON.stringify(tiyData.tParam.paramProduct.customSize),
        productSizeDetail:JSON.stringify(detailData),
        productSizeRow:rowCount,
        productSizeColumn:columnCount,
        title:tiyData.tParam.productSizeTable.title,
        subTitle:tiyData.tParam.productSizeTable.subTitle,
        productSizeImages:tiyData.tParam.paramProduct.productSizeImages,
        sequence:tiyData.tParam.paramProduct.sequence,
        keyword:tiyData.tParam.paramProduct.keyword,
        note:tiyData.tParam.paramProduct.note,
        description: tiyData.tParam.paramProduct.description,
        showImage: tiyData.tParam.paramProduct.showImage,
        mainImages: tiyData.tParam.paramProduct.mainImages,
        detailImages: tiyData.tParam.paramProduct.detailImages,
        videos:tiyData.tParam.paramProduct.videos
      };
      if(paramProduct.comparePrice.isUploadComparePrice){ //只有启用比价数据时才设置
        param.comparePrice = paramProduct.comparePrice;
      }
      self.$apiProduct.saveEditProduct(param)
        .then(function (response) {
          tiyData.tStatus.modalModify.isLoading = false;
          if (response.success) {
            tiyData.tParam.paramProduct.id = response.result;
            tiyData.tStatus.modalModify.isEditDetail = true;
            tiyData.tStatus.modalModify.closable = true;
            self.$Modal.success({content:'保存成功!可以继续编辑产品详情！'});
            self.$emit("reload-list");
            self.$Spin.hide();
          } else {
            self.$Modal.error({content:response.errorMessage});
            self.$Spin.hide();
          }
        });

    } else {
      self.$Spin.hide();
      tiyData.tStatus.modalModify.isLoading = false;
    }
  });
};

export const makeClassificationTree = (self, tiyData) =>{
  let classifications = self.$store.getters.product.classifications;
  let level1Resource = classifications.filter(category => category.level == 1);
  let level2Resource = classifications.filter(category => category.level == 2);
  let level3Resource = classifications.filter(category => category.level == 3);
  let dataResult = [];
  tiyData.tData.classificationTreeShow.splice(0,tiyData.tData.classificationTreeShow.length);
  tiyData.tData.classificationTree.splice(0, tiyData.tData.classificationTree.length);
  level1Resource.forEach(function(classificationLevel1){
    let dataLevel2 = [];
    level2Resource.filter(classification => classification.parentId == classificationLevel1.id).forEach(function (itemLevel2) {
      let dataLevel3 = [];
      level3Resource.filter(classification => classification.parentId == itemLevel2.id).forEach(function (itemLevel3) {
        if(tiyData.tParam.paramProduct.classificationIds.length!=0&&tiyData.tParam.paramProduct.classificationIds.indexOf(itemLevel3.id)!=-1){
          dataLevel3.push({value: itemLevel3.id, title: itemLevel3.name,level:3,checked: true});
          tiyData.tData.classificationTreeShow.push({level1:classificationLevel1.name,level2:itemLevel2.name,level3:itemLevel3.name});
          // flag=true;
        }else{
          dataLevel3.push({value: itemLevel3.id, title: itemLevel3.name,level:3,disabled:itemLevel3.type==2});
        }
      });
      dataLevel2.push({value: itemLevel2.id, title: itemLevel2.name,children: dataLevel3 ,level:2,disabled:itemLevel2.type==2});
    });
    tiyData.tData.classificationTree.push({value:classificationLevel1.id,title:classificationLevel1.name,children:dataLevel2,
      level:1,disabled:classificationLevel1.type==2,disableCheckbox:classificationLevel1.type==2});
  });
}

/**
 * 构造尺码详情表，对尺码表结构作任何变动后都需要调用此方法，重新构造表结构
 * @param self
 * @param tiyData
 */
export const createSizeTableTitles = (self, tiyData) => {
  tiyData.tTable.sizeTableTitles.length = 0;
  let columnCount = tiyData.tParam.productSizeTable.columnCount;
  let rowCount = tiyData.tParam.productSizeTable.rowCount;
  let sizeTableTitles = [];
  for (let i = 0; i < columnCount; i++) {
    let name='第 '+(i+1)+' 列';
    let columni = {
      title: name,
      key: 'Column' + i,
      width:  i===0?200:160,
      align: 'center',
      render: (h, params) => {
        let holder = params.index===0? '尺码(如:XL)':'建议值';
        if(i===0){
          holder = '属性(如:Length)'
        }
        if(i===0&&params.index===0){
          return h('span','属性\\尺码');
        }

        if(params.index === rowCount){
          if(i === 0 ){
            return h("div", "");
          } else {
            return h('Button', {
              props: {type: 'info', size: 'small', icon: "flash",},
              style: {marginTop:'6px',marginBottom:'6px'},
              on: {
                click: () => {
                  deleteCurrentSizeRow(self, tiyData, params.column._index);
                }
              }
            }, "删除列")
          }

        }

        return h('Input',{
          props: {
            placeholder: holder,
            value: params.row['Column' + i],
            disabled:(i===0&&params.index===0)?true:false,
            prefix:(i===0&&params.index!==0)||(i!==0&&params.index===0)?'md-alert':''
          },
          style:{fontSize:'0.85rem'},
          on: {
            'on-blur':(event) => {
              tiyData.tData.productSizeDetail[params.index]['Column' + i] =  event.target.value;
              // params.row[name] = event.target.value;
            }
          }
        })
      }

    };
    tiyData.tTable.sizeTableTitles.push(columni)
  }

  let action={
    title: '操作',
    key: 'action',
    width: 110,
    render: (h, params) => {
      if(params.index===0){
        return h('span','');
      }

      if(params.index === rowCount){
        return h("div", "");
      }

      return h('Button', {
        props: {type: 'info', size: 'small', icon: "flash",},
        style: {marginTop:'6px',marginBottom:'6px', },
        on: {
          click: () => {
            tiyData.tData.productSizeDetail.splice(params.index,1);
            tiyData.tParam.productSizeTable.rowCount--;
            createSizeTableTitles(self, tiyData);
          }
        }
      }, "删除行")

    },
    align: 'center'
  }
  tiyData.tTable.sizeTableTitles.push(action);
}

export const createSizeTableData = (tiyData) => {
  tiyData.tData.productSizeDetail.length = 0;
  let rowCount = tiyData.tParam.productSizeTable.rowCount;
  let columnCount = tiyData.tParam.productSizeTable.columnCount;

  for(let i=0;i<rowCount + 1;i++ ){ //最后多一行，为删除列按钮
    let rowi={};
    for(let j=0;j<columnCount;j++ ){
      let name='Column'+j;
      rowi[name]='';
    }
    tiyData.tData.productSizeDetail.push(rowi);
  }
}

export const getProductSizes = (self,tiyData) => {
  let productId = tiyData.tParam.paramProduct.id;
  self.$ySpliceAll(tiyData.tParam.productColor.productSizes);
  self.$apiProduct.getProductSizes({
    productId:productId
  }) .then(function (response) {
    response.result.forEach(function(item){
      tiyData.tParam.productColor.productSizes.push({
        id:item.id,
        selfDesignSize:item.selfDesignSize,
        stock:'',
        sizeName:item.name,
        sysSizeType:item.sysSizeType
      });
    })
  })
}

/**
 * 改变色卡状态
 * @param self
 * @param tiyData
 */
export const webColorState= (self,tiyData) => {// 100 上架  200 下架 300 回收站
  self.$Spin.show();
  self.$apiProduct.changeProductColorState({
    "productId": tiyData.tStatus.modalAction.productColor.productId,
    "productCode": tiyData.tStatus.modalAction.productColor.productCode,
    "colorId": tiyData.tStatus.modalAction.productColor.colorId,
    "colorName": tiyData.tStatus.modalAction.productColor.colorName,
    "state": tiyData.tStatus.modalAction.productColor.state
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Modal.success({content:'提交成功!'});
      self.$apiProduct.getProductColorsByProductId({"productId":tiyData.tStatus.modalAction.productColor.productId})
        .then(function(response){
          if(response.success){
            tiyData.tData.productColorList.length=0;
            response.result.forEach(function(item){
              tiyData.tData.productColorList.push(item);
            })
          }
        })
    } else {
      self.$Modal.error({content:response.errorMessage});
    }
  });
}
/**
 * 色卡移入回收站
 * @param self
 * @param tiyData
 */
export const colorToRecycle= (self,tiyData) => {
  self.$Spin.show();
  self.$apiProduct.changeProductColorState({
    "productId": tiyData.tStatus.modalAction.productColor.productId,
    "productCode": tiyData.tStatus.modalAction.productColor.productCode,
    "colorId": tiyData.tStatus.modalAction.productColor.colorId,
    "colorName": tiyData.tStatus.modalAction.productColor.colorName,
    "state": tiyData.tStatus.modalAction.productColor.state
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Modal.success({content:'提交成功!'});
      self.$apiProduct.getProductColorsByProductId({"productId":tiyData.tStatus.modalAction.productColor.productId})
        .then(function(response){
          if(response.success){
            tiyData.tData.productColorList.length=0;
            response.result.forEach(function(item){
              tiyData.tData.productColorList.push(item);
            })
          }
        })
    } else {
      self.$Modal.error({content:response.errorMessage});
    }
  });
}

export const action = (self, tiyData, type, index) => {
  let title = '';
  let content = '';
  let product;
  let productColor;
  if (2 >= type) {
    product = tiyData.tData.productList[index];
  } else {
    productColor = tiyData.tData.productColorList[index];
  }
  switch (type) {
    case 7:
      title = '确认上/下架色卡';
      content = '确定' + (productColor.state == 100 ? '下架' : '上架') + '色卡' + productColor.colorName;
      if (productColor.state == 100) {
        tiyData.tStatus.modalAction.productColor.state = 200;
      } else if (productColor.state == 200) {
        tiyData.tStatus.modalAction.productColor.state = 100;
      }
      break;
    case 8:
      title = '确认删除';
      content = '移入后可从回收站找回!是否确定将色卡' + productColor.colorName + '移入回收站';
      tiyData.tStatus.modalAction.productColor.state = 300;
      break;
    default:
      break;
  }
  if (2 >= type) {
    tiyData.tStatus.modalAction.product.id = product.id;
    tiyData.tStatus.modalAction.product.code = product.code;
    tiyData.tStatus.modalAction.product.state = product.state;
  } else {
    tiyData.tStatus.modalAction.productColor.productId = productColor.productId;
    tiyData.tStatus.modalAction.productColor.productCode = tiyData.tParam.paramProduct.productCode;
    tiyData.tStatus.modalAction.productColor.colorId = productColor.id;
    tiyData.tStatus.modalAction.productColor.colorName = productColor.colorName;
  }
  tiyData.tStatus.modalAction.title = title;
  tiyData.tStatus.modalAction.content = content;
  tiyData.tStatus.modalAction.type = type;
  tiyData.tStatus.modalAction.isShow = true;

}

/**
 * 色卡排序
 * @param self
 * @param tiyData
 */
export const colorSort= (self,tiyData) => {
  self.$Spin.show();
  var colorSequenceList=new Array()
  if(tiyData.tData.productColorSortList.length>0){
    tiyData.tData.productColorSortList.forEach(function(item,index){
      colorSequenceList.push({
        'id':item.id,
        'sequence':index
      })
      })
    self.$apiProduct.batchSequenceColor({
      "colorSequenceList":colorSequenceList
    }).then(function (response) {
      self.$Spin.hide();
      if (response.success) {
        self.$Modal.success({content:'排序成功!'});
        tiyData.tData.productColorList.splice(0,tiyData.tData.productColorList.length)
        tiyData.tData.productColorSortList.forEach(function(item){
          tiyData.tData.productColorList.push(item);
        })
      } else {
        self.$Modal.error({content:response.errorMessage});
      }
    });
  }
}

/**
 * 删除尺码详情表格中一列数据
 * @param self
 * @param tiyData
 * @param rowIndex
 */
function deleteCurrentSizeRow(self, tiyData, rowIndex){
  // if(tiyData.tTable.sizeTableTitles.length <= 3){
  //   self.$Modal.error({content:"自定义尺码内容列不能全部删除"});
  //   return;
  // }
  for (let i = 0; i < tiyData.tData.productSizeDetail.length; i++){
    let row = tiyData.tData.productSizeDetail[i];
    let newRow = new Object();

    for (let j = 0; j < tiyData.tParam.productSizeTable.columnCount -1 ; j++){
      let name = "Column" + j;
      if(j < rowIndex){
        newRow[name] = row[name];
        continue;
      }
      newRow[name] = row["Column" + (j + 1)];
    }
    tiyData.tData.productSizeDetail.splice(i, 1, newRow);
  }


  tiyData.tTable.sizeTableTitles.splice(rowIndex, 1);
  for(let i = rowIndex; i < tiyData.tTable.sizeTableTitles.length - 1; i++){
    tiyData.tTable.sizeTableTitles[i].title = "第"+(i+1)+"列";
  }

  tiyData.tParam.productSizeTable.columnCount = parseInt(tiyData.tParam.productSizeTable.columnCount) - 1;
  createSizeTableTitles(this, tiyData);
}

/**
 * 查询产品货源信息
 * @param self
 * @param tiyData
 */
export const getProductSupplys = (self,tiyData) => {
  let productId = tiyData.tParam.paramProduct.id;
  tiyData.tData.productSupplyList.splice(0, tiyData.tData.productSupplyList.length);
  self.$apiProduct.getProductSupplys({
    productId:productId
  }) .then(function (response) {
    if(response.success){
      response.result.forEach(function(item){
        tiyData.tData.productSupplyList.push(item);
      })
    } else {
      self.$Message.error("查询产品货源失败。" + response.errorMessage);
    }
  })
}

/**
 * 删除一条产品货源信息
 * @param self
 * @param tiyData
 * @param id
 */
export const deleteProductSupply = (self, tiyData, id) => {
  self.$Spin.show();
  self.$apiProduct.deleteProductSupply({
    "id":id, "productCode": tiyData.tParam.paramProduct.productCode
  }) .then(function (response) {
    self.$Spin.hide();
    if(response.success){
      self.$Message.success("成功删除货源");
      getProductSupplys(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 保存一条产品货源信息
 * @param self
 * @param tiyData
 */
export const saveProductSupply = (self, tiyData) => {
  if(!tiyData.tParam.productSupply.url){ //目前必须有采购链接
    self.$Modal.error({
      title: "error",
      content: "填入有效的采购链接",
      width:500
    });
    return;
  }
  if(tiyData.tParam.productSupply.referencePrice !== null && tiyData.tParam.productSupply.referencePrice !== ''){
    // console.log(tiyData.tParam.productSupply.referencePrice);
    let reg = /^(0|[1-9]\d*)(\s|$|\.\d{1,2}\b)$/;
    if(!reg.test(tiyData.tParam.productSupply.referencePrice)){
      self.$Modal.error({
        title: "error",
        content: "填入正确的采购价格",
        width:500
      });
      // self.$refs['productSupplyForm'].resetFields();
      return;
    }
  }
  self.$Spin.show();
  let data = {
    "isNew" : tiyData.tStatus.supplyEditModal.isNew,
    "productCode": tiyData.tParam.paramProduct.productCode,
    "supply" : tiyData.tParam.productSupply
  }
  self.$apiProduct.saveProductSupply(data).then(function (response) {
    self.$Spin.hide();
    if(response.success){
      self.$Message.success("成功保存货源");
      getProductSupplys(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 查询产品积压库存
 * @param self
 * @param tiyData
 */
export const getProductOverstock = (self,tiyData) => {
  let productId = tiyData.tParam.paramProduct.id;
  tiyData.tData.productOverstock.splice(0, tiyData.tData.productOverstock.length);
  tiyData.tData.productOverstockSpan.splice(0, tiyData.tData.productOverstockSpan.length);
  self.$apiProduct.getProductOverstock({
    productId:productId
  }) .then(function (response) {
    if(response.success){
      response.result.forEach(function(item){
        tiyData.tData.productOverstock.push(item);
        tiyData.tData.productOverstockSpan.push(1);
      });

      //计算需要合并的色卡列
      let color = tiyData.tData.productOverstock[0].color_id;
      let colorIndex = 0;
      for(let j = 1; j < tiyData.tData.productOverstock.length; j++) {
        let tr = tiyData.tData.productOverstock[j];
        if (tr.color_id == color) {
          tiyData.tData.productOverstockSpan[colorIndex]++;
          tiyData.tData.productOverstockSpan[j] = 0;
        } else {
          color = tr.color_id;
          colorIndex = j;
        }
      }
    } else {
      self.$Message.error("查询产品积压库存失败。" + response.errorMessage);
    }
  })
}


/**
 * 查询产品积压库存
 * @param self
 * @param tiyData
 */
export const saveProductOverstock = (self,tiyData) => {
  let data = {
    "code": tiyData.tParam.paramProduct.productCode,
    "overstocks" : tiyData.tData.productOverstock
  };
  self.$apiProduct.saveProductOverstock(data) .then(function (response) {
    if(response.success){
      self.$Message.success("成功保存产品积压库存");
    } else {
      self.$Message.error("查询产品积压库存失败。" + response.errorMessage);
    }
  })
}

export const saveAddProduct = (self, tiyData) => {
  let params = tiyData.tParam.paramProduct;
  self.$Spin.show();
  self.$apiProduct.saveAddProduct(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("产品保存成功！");
      modifyProduct(self, tiyAddEditData, response.result, true);
      tiyData.tStatus.modalAdd.isShow = false;
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}
